const csInterface = new CSInterface();
const extensionPath = csInterface.getSystemPath(SystemPath.EXTENSION);
const subtitleAgentPath = '/Users/fanjunwei/Documents/PythonProjects/subtitle_agent/subtitle_agent.py';
const pythonPath = '/Users/fanjunwei/Documents/PythonProjects/subtitle_agent/venv/bin/python';
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');

// 添加调试函数
function log(message) {
    console.log(message);
    const statusElement = document.getElementById('status');
    const timestamp = new Date().toLocaleTimeString();
    statusElement.innerHTML += `[${timestamp}] ${message}<br>`;
    statusElement.scrollTop = statusElement.scrollHeight;
}

// 获取参考文案
function getReferenceFile() {
    return window.referenceFilePath || null;
}

document.getElementById('generateSubtitles').addEventListener('click', async () => {
    try {
        log('开始处理...');
        console.group('生成字幕过程');
        log('扩展路径: ' + extensionPath);
        log('脚本路径: ' + subtitleAgentPath);

        // 获取系统临时目录
        const tempPath = os.tmpdir() + '/subtitle_agent_temp';
        // 删除临时目录
        if (fs.existsSync(tempPath)) {
            fs.rmdirSync(tempPath, { recursive: true });
        }
        fs.mkdirSync(tempPath, { recursive: true });
        log('临时目录路径: ' + tempPath);

        // 获取参考文案文件
        const referenceFile = getReferenceFile();
        if (referenceFile) {
            log('使用参考文件: ' + referenceFile);
        } else {
            log('未选择参考文件');
        }

        log('正在导出序列...');
        console.time('导出序列');
        const result = await evalExtendScript(`exportCurrentSequence("${tempPath}")`);
        console.timeEnd('导出序列');
        log('导出序列结果: ' + result);
        
        let response;
        try {
            response = JSON.parse(result);
        } catch (parseError) {
            console.error('JSON解析错误:', parseError);
            log('JSON解析错误，原始返回值: ' + result);
            throw new Error('返回数据格式错误: ' + parseError.message);
        }
        
        if (!response.success) {
            throw new Error(response.error || '未知错误');
        }

        log('正在生成字幕...');
        const audioPath = response.path;
        const srtPath = audioPath.replace('.mp3', '_subtitles.srt');
        
        log('音频路径: ' + audioPath);
        log('字幕路径: ' + srtPath);
        
        // 检查Python是否可用
        const pythonVersionProcess = spawn(pythonPath, ['--version']);
        pythonVersionProcess.on('error', (err) => {
            log('Python执行错误: ' + err.message);
        });
        
        // 准备Python脚本参数
        const pythonArgs = [
            subtitleAgentPath,
            audioPath,
            '--output',
            srtPath,
            '--model',
            'small'
        ];
        
        // 如果有参考文件，添加参考文件参数
        if (referenceFile) {
            pythonArgs.push('--ref');
            pythonArgs.push(referenceFile);
        }
        
        // 调用Python脚本生成字幕
        log("pythonPath: " + pythonPath);
        log("pythonArgs: " + pythonArgs);
        const pythonProcess = spawn(pythonPath, pythonArgs);

        pythonProcess.stdout.on('data', (data) => {
            log('输出: ' + data.toString());
        });

        pythonProcess.stderr.on('data', (data) => {
            log('错误: ' + data.toString());
        });

        pythonProcess.on('error', (error) => {
            console.error('Python进程错误:', error);
            log('进程错误: ' + error.message);
            if (fs.existsSync(audioPath)) {
                fs.unlinkSync(audioPath);
            }
        });

        pythonProcess.on('close', (code) => {
            console.groupEnd();
            if (code === 0) {
                log('字幕生成完成！');
                document.getElementById('importSubtitles').disabled = false;
                window.generatedSrtPath = srtPath;
            } else {
                log('字幕生成失败！退出代码: ' + code);
            }
            if (fs.existsSync(audioPath)) {
                fs.unlinkSync(audioPath);
            }
        });
    } catch (error) {
        console.error('完整错误信息:', error);
        log('错误: ' + error.message);
        console.groupEnd();
    }
});

document.getElementById('importSubtitles').addEventListener('click', async () => {
    try {
        if (!window.generatedSrtPath) {
            throw new Error('没有找到生成的字幕文件');
        }

        log('正在导入字幕...');
        log('字幕文件路径: ' + window.generatedSrtPath);
        const result = await evalExtendScript(`importSubtitles("${window.generatedSrtPath}")`);
        log('导入结果: ' + result);
        const response = JSON.parse(result);
        
        if (!response.success) {
            throw new Error(response.error);
        }

        log('字幕导入完成！');
    } catch (error) {
        log('错误: ' + error.message);
        console.error(error);
    }
});
document.getElementById('test').addEventListener('click', () => {
    const tempDir = os.tmpdir();
    log('临时目录: ' + tempDir);
    evalExtendScript('test()');
});
document.getElementById('moveSubtitles').addEventListener('click', () => {
    evalExtendScript('moveSubtitles()');
});

function updateStatus(message) {
    const statusElement = document.getElementById('status');
    statusElement.textContent = message;
    statusElement.scrollTop = statusElement.scrollHeight;
}

function evalExtendScript(script) {
    return new Promise((resolve, reject) => {
        csInterface.evalScript(script, (result) => {
            log('ExtendScript返回值: ' + result);
            if (result === 'EvalScript error.' || !result) {
                reject(new Error('ExtendScript执行失败，请检查ExtendScript调试器输出'));
            } else {
                resolve(result);
            }
        });
    });
}

// 添加重新加载JSX文件的功能
function reloadJSX() {
    try {
        const jsxPath = extensionPath + '/jsx/main.jsx';
        log('重新加载JSX文件: ' + jsxPath);
        const command = `$.evalFile("${jsxPath}")`;
        csInterface.evalScript(command, (result) => {
            if (result === 'undefined' || result === 'true') {
                log('JSX重新加载成功');
            } else {
                log('JSX重新加载失败: ' + result);
            }
        });
    } catch (error) {
        log('重新加载JSX文件失败: ' + error.message);
        console.error('重新加载JSX文件错误:', error);
    }
}

// 初始化参考文件上传功能
function initReferenceFileUpload() {
    const referenceFileInput = document.getElementById('referenceFile');
    const fileNameDisplay = document.getElementById('fileName');
    
    // 监听文件上传
    referenceFileInput.addEventListener('change', (event) => {
        if (event.target.files.length > 0) {
            const file = event.target.files[0];
            fileNameDisplay.textContent = file.name;
            
            // 保存文件路径供后续使用
            window.referenceFilePath = file.path;
            log('已选择参考文件: ' + file.path);
        } else {
            fileNameDisplay.textContent = '';
            window.referenceFilePath = null;
        }
    });
}

// 初始化时检查环境
window.onload = async () => {
    try {
        log('插件初始化...');
        log('CEP版本: ' + csInterface.getHostEnvironment().appVersion);
        log('操作系统: ' + csInterface.getOSInformation());
        
        // 初始化参考文件上传功能
        initReferenceFileUpload();
        
        // 添加调试按钮事件处理
        document.getElementById('reloadDebug').addEventListener('click', () => {
            reloadJSX();
            setTimeout(() => {
                window.location.reload();
            }, 500);
        });
        
        // 初始化时加载JSX文件
        await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒确保环境准备好
        reloadJSX();
    } catch (error) {
        log('初始化错误: ' + error.message);
        console.error('初始化错误:', error);
    }
}; 